/**
 *
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package vip.web3.common.utils;

import com.aliyun.oss.OSSClient;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云OSS 存储
 */
@Component
public class AliyunOssUtils {

     private OSSClient client;

    // 文件名分隔符
    public static String cut = "_";

    //阿里云绑定的域名
    private static String aliyunDomain = "https://-static.oss-cn-hongkong.aliyuncs.com";

    //阿里云EndPoint
    private static String aliyunEndPoint = "oss-cn-hongkong.aliyuncs.com";

    //阿里云AccessKeyId
    private static String aliyunAccessKeyId = "oss";

    //阿里云AccessKeySecret
    private static String aliyunAccessKeySecret = "oss";

    //阿里云BucketName
    private static String aliyunBucketName = "-static";

    public AliyunOssUtils(){
        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(aliyunEndPoint, aliyunAccessKeyId, aliyunAccessKeySecret);
    }

    /**
     * 阿里云文件上传
     * @param data byte 数组
     * @param suffix 文件后缀名
     * @return
     */
    public R uploadByte(byte[] data, String suffix) {
        return uploadStream(new ByteArrayInputStream(data), suffix);
    }

    /**
     *
     * @param inputStream 文件流
     * @param suffix 文件后缀名
     * @return
     */
    public R uploadStream(InputStream inputStream, String suffix) {
        R returnMsg = new R();
        String fileName = getFileName(suffix);
        try {
            client.putObject(aliyunBucketName, fileName, inputStream);
        } catch (Exception e){
            returnMsg = R.error("文件上传失败");
            return returnMsg;
        }
        returnMsg.put("dirPath", aliyunDomain + "/" + fileName);
        return returnMsg;
    }

    /**
     * 获取文件名
     * @param suffix
     * @return
     */
    public String getFileName(String suffix){
        long uniqueTime = System.currentTimeMillis();
        int uniqueNum = (int)((Math.random() * 9 + 1) * 100000);
        return uniqueTime + cut + uniqueNum + suffix;
    }

}
